<template>
    <el-dialog :title="title" v-model="visible" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备ID" prop="assetId">
          <el-input v-model="form.assetId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="备件ID" prop="spareId">
          <el-input v-model="form.spareId" placeholder="请输入备件ID" />
        </el-form-item>
        <el-form-item label="初始日期" prop="initialDate">
          <el-date-picker v-model="form.initialDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择初始日期" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="form.score" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入等级" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, defineExpose, defineEmits } from 'vue'
  import { ElMessage } from 'element-plus'
  import { addAssessment, updateAssessment } from '@/api/sbtz/assessment'
  
  const visible = ref(false)
  const title = ref('新增设备评估')
  
  const formRef = ref(null)
  const form = reactive({
    id: null,
    assetId: '',
    spareId: '',
    initialDate: '',
    score: '',
    grade: '',
    remark: ''
  })
  
  const rules = {
    assetId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
    spareId: [{ required: true, message: '备件ID不能为空', trigger: 'blur' }],
    initialDate: [{ required: true, message: '初始日期不能为空', trigger: 'blur' }],
    score: [{ required: true, message: '分数不能为空', trigger: 'blur' }],
    grade: [{ required: true, message: '等级不能为空', trigger: 'blur' }]
  }
  
  const emit = defineEmits(['refresh'])
  
  function reset(extra = {}) {
    Object.assign(form, {
      id: null,
      assetId: extra.assetId || '',
      spareId: '',
      initialDate: '',
      score: '',
      grade: '',
      remark: ''
    })
  }
  
  function open(row) {
    if (row && row.id) {
      title.value = '修改设备评估'
      Object.assign(form, row)
    } else {
      title.value = '新增设备评估'
      reset(row || {})
    }
    visible.value = true
  }
  
  function submit() {
    formRef.value.validate(valid => {
      if (!valid) return
      const api = form.id ? updateAssessment : addAssessment
      api(form).then(() => {
        ElMessage.success(form.id ? '修改成功' : '新增成功')
        visible.value = false
        emit('refresh')
      })
    })
  }
  
  defineExpose({ open })
  </script>
  